package handler

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"github.com/share309/gojwt"
	"house/api/requset"
	"house/api/resp"
	"house/consts"
	"house/internal/dao"
	"house/internal/model"
	"time"
)

// 注册
func Register(c *gin.Context) {
	//接收参数
	var req requset.RegisterReq
	if err := c.ShouldBind(&req); err != nil {
		resp.Error(c, 10000, "验证失败", err.Error())
		return
	}

	//业务逻辑
	var user model.User
	dao.GetOneByFields(&model.User{Mobile: req.Mobile}, &user)
	if user.Id > 0 {
		resp.Error(c, 10000, "用户已存在", nil)
		return
	}

	if req.Password != req.Confirm {
		resp.Error(c, 10000, "两次密码输入不一致", nil)
		return
	}

	result := dao.Create(&model.User{
		Mobile:   req.Mobile,
		Password: req.Password,
		UType:    req.UType,
	})
	if !result {
		resp.Error(c, 10000, "注册失败", false)
		return
	}

	//返回参数
	resp.Success(c, true)
}

// 登录
func Login(c *gin.Context) {
	//接收参数
	var req requset.LoginReq
	if err := c.ShouldBind(&req); err != nil {
		resp.Error(c, 10000, "验证失败", err.Error())
		return
	}

	//业务逻辑
	var user model.User
	dao.GetOneByFields(&model.User{
		Mobile:   req.Mobile,
		Password: req.Password,
	}, &user)
	if user.Id == 0 {
		resp.Error(c, 10000, "用户不存在", nil)
		return
	}

	if req.Password != user.Password {
		resp.Error(c, 10000, "账号密码错误", nil)
		return
	}

	token, err := gojwt.NewJWT(consts.JWT_KEY).CreateToken(gojwt.CustomClaims{
		ID: user.Id,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Unix() + 86400*3,
		},
	})
	if err != nil {
		resp.Error(c, 10000, "token生成失败", nil)
		return
	}

	//返回
	resp.Success(c, token)

}

// 刷新token
func RefreshToken(c *gin.Context) {
	token, err := gojwt.NewJWT(consts.JWT_KEY).CreateToken(gojwt.CustomClaims{
		ID: c.GetUint("userId"),
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Unix() + 86400*3, //3天有效期
		},
	})
	if err != nil {
		resp.Error(c, 10000, "token生成失败", nil)
		return
	}

	//返回
	resp.Success(c, token)
}
